package cn.chinaiptv.apkmanager.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import cn.chinaiptv.apkmanager.bean.Epgbg;

public class EPGbgDao {

	static Session session = null;
	static {
		Configuration cfg = new Configuration().configure();

		SessionFactory factory = cfg.buildSessionFactory();
		session = factory.openSession();
	}

	/**
	 * 添加数据
	 * 
	 * @param demo
	 */
	public static boolean save(Epgbg bean) {
		boolean result;
		try {
			// 开启事务
			session.beginTransaction();
			session.save(bean);
			// 提交事务
			session.getTransaction().commit();
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			// 回滚事务
			session.getTransaction().rollback();
			result = false;
		} finally {
			if (session != null) {
				if (session.isOpen()) {
					// 关闭session
					session.close();
				}
			}
		}
		return result;
	}

	/**
	 * 查询数据
	 *
	 * @param id
	 * @param page
	 * @param pageszie
	 */
	public static ArrayList<Epgbg> find(int page, int pageszie) {
		ArrayList<Epgbg> beans = new ArrayList<Epgbg>();
		try {
			int startRow = (page - 1) * pageszie;
			// 开启事务
			session.beginTransaction();
			// String hql = "from EPGRecommBean as epgrecommbean where 1=1 ";
			// if (name != "") {
			// hql = hql + " and sqldemo.demo_name like '%" + name + "%'";
			// }
			String hql = "from Epgbg";
			Query query = session.createQuery(hql).setFirstResult(startRow)
					.setMaxResults(pageszie);
			List<Epgbg> list = query.list();

			for (Epgbg bean : list) {
				beans.add(bean);
			}
			// 提交事务
			session.getTransaction().commit();

		} catch (Exception e) {
			e.printStackTrace();
			// 回滚事务
			session.getTransaction().rollback();
		} finally {
			if (session != null) {
				if (session.isOpen()) {
					// 关闭session
					session.close();
				}
			}
		}
		return beans;
	}

	/**
	 * 删除数据
	 *
	 * @param demo
	 */
	public static boolean del(int id) {
		boolean result;
		try {
			// 开启事务
			session.beginTransaction();

			String sql = "delete from epgbg where epgbg.epgbg_id= ?";
			SQLQuery query = session.createSQLQuery(sql);
			query.setInteger(0, id);
			query.executeUpdate(); // 提交事务
			session.getTransaction().commit();
			result = true;

		} catch (Exception e) {
			e.printStackTrace();
			// 回滚事务
			session.getTransaction().rollback();
			result = false;
		} finally {
			if (session != null) {
				if (session.isOpen()) {
					// 关闭session
					session.close();
				}
			}
		}
		return result;
	}

}
